<template>
    <div class="appointment">
        <div class="back">
            <span @click="backToHome"><el-icon><Back/></el-icon>返回</span>
        </div>
        <el-container>
            <el-main>
                <el-steps :active="activeStep" finish-status="success" class="steps">
                    <el-step title="选择医院"></el-step>
                    <el-step title="选择科室"></el-step>
                    <el-step title="选择医生"></el-step>
                    <el-step title="确认预约"></el-step>
                </el-steps>

                <!-- 选择医院 -->
                <div v-if="activeStep === 0" class="step-content">
                    <div class="search-bar">
                        <el-input
                            v-model="searchHospital"
                            placeholder="请输入医院名称"
                            :prefix-icon="Search"
                            clearable
                            class="search-input"
                            size="large"
                        />
                    </div>
                    <el-empty v-if="filteredHospitals?.length === 0" description="暂无数据" />
                    <el-row :gutter="20" class="hospital-list" v-else>
                        <el-col :span="8" v-for="hospital in filteredHospitals" :key="hospital.id">
                            <el-card class="hospital-card" @click="selectHospital(hospital)" :body-style="{ padding: '0px' }">
                                <div class="hospital-info">
                                    <img :src="hospitalUrl(hospital.name) || defaultHospitalImage" class="hospital-image">
                                    <div class="hospital-detail">
                                        <h3>{{ hospital.name }}</h3>
                                        <p class="address-text">
                                            <el-icon><Location /></el-icon>
                                            {{ hospital.address }}
                                        </p>
                                        <p class="level-text">
                                            <el-tag size="small">{{ hospital.level }}</el-tag>
                                        </p>
                                    </div>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>

                <!-- 选择科室 -->
                <div v-if="activeStep === 1" class="step-content">
                    <!-- <div class="step-title">
                        <el-text class="mx-1" type="success">{{ selectedHospital.name }}</el-text>
                    </div> -->
                    <div class="search-bar">
                        <el-input
                            v-model="searchDepartment"
                            placeholder="请输入科室名称"
                            :prefix-icon="Search"
                            clearable
                            class="search-input"
                            size="large"
                        />
                        <el-button @click="goBack(0)" size="large">返回上一步</el-button>
                    </div>
                    <el-empty v-if="filteredDepartments?.length === 0" description="暂无数据" />
                    <el-row :gutter="20" class="department-list" v-else>
                        <el-col :span="6" v-for="dept in filteredDepartments" :key="dept.id" v-show="dept.doctors_count">
                            <el-card class="department-card" @click="selectDepartment(dept)">
                                <div class="department-info">
                                    <!-- <el-icon :size="30"><OfficeBuilding /></el-icon> -->
                                     <img :src="depUrl(dept.name)" style="width: 50px;" alt="">
                                    <h3>{{ dept.name }}</h3>
                                    <p>{{ dept.description }}</p>
                                    <p class="doctor-count">在职医生: {{ dept.doctors_count }}人</p>
                                </div>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>

                <!-- 选择医生 -->
                <div v-if="activeStep === 2" class="step-content">
                    <div class="search-bar">
                        <el-input
                            v-model="searchDoctor"
                            placeholder="请输入医生姓名"
                            :prefix-icon="Search"
                            clearable
                            class="search-input"
                        />
                        <el-button @click="goBack(1)" size="large">返回上一步</el-button>
                        <el-segmented v-model="selectedDate" :options="options" size="default" block>
                            <template #default="scope">
                                <div class="flex flex-col items-center gap-2 p-2">
                                    <div>{{ scope.item.label.slice(0,5) }}</div>
                                    <div>{{ scope.item.label.slice(5) }}</div>
                                </div>
                            </template>
                        </el-segmented>
                    </div>
                    <el-empty v-if="doctors?.length === 0 || filteredDoctors?.length === 0" description="暂无数据" />
                    <el-row :gutter="20" class="doctor-list" v-else>
                        <el-col :span="8" v-for="doctor in filteredDoctors" :key="doctor.id"
                        >
                            <el-card class="doctor-card">
                            <div class="doctor-info">
                                <img :src="doctor.gender === 'M' ? doctorMan : doctorWoman" class="doctor-avatar"
                                />
                                <div class="doctor-detail">
                                <h3>{{ doctor.name }}</h3>
                                <p>
                                    <el-tag size="small" type="success">{{ doctor.position }}</el-tag>
                                </p>
                                <p class="specialty">{{ doctor.specialty }}</p>
                                <p class="schedule">
                                    <el-tag size="small" type="info">
                                    出诊时间: {{ doctorSchedules[doctor.id] || '暂无排班' }}
                                    </el-tag>
                                </p>
                                </div>
                            </div>
                            <div class="action-buttons">
                                <el-button type="primary" @click="makeAppointment(doctor)">预约</el-button>
                                <el-button @click="showDoctorDetail(doctor)">查看详情</el-button>
                            </div>
                            <!-- 预约时间选择对话框 -->
                            <Teleport to="body" v-if="appointmentDialogVisible">
                                <el-dialog v-model="appointmentDialogVisible" title="选择预约时间" width="40%">
                                    <el-radio-group v-model="selectedTime" style="margin-left: 5%;">
                                        <el-radio
                                        v-for="time in timeList"
                                        :key="time.value"
                                        :value="time.value"
                                        size="large"
                                        border
                                        style="flex: 0 0 45%; margin: 10px 10px;"
                                        :disabled="timeDisabledStatus[time.value]">
                                            {{ time.start.slice(0, 5) }} - {{ time.end.slice(0, 5) }}
                                        </el-radio>
                                    </el-radio-group>
                                    <template #footer>
                                        <span class="dialog-footer">
                                            <el-button @click="appointmentDialogVisible = false">取消</el-button>
                                            <el-button type="primary" @click="confirmAppointment">确认预约</el-button>
                                        </span>
                                    </template>
                                </el-dialog>
                            </Teleport>
                            </el-card>
                        </el-col>
                    </el-row>
                </div>

                <!-- 确认预约 -->
                <div v-if="activeStep === 3" class="step-content">
                    <el-result
                        icon="success"
                        title="预约成功"
                        sub-title="您的预约信息已提交成功"
                    >
                        <template #extra>
                            <el-button type="primary" @click="goToUserCenter">查看预约记录</el-button>
                            <el-button @click="resetAppointment">继续预约</el-button>
                        </template>
                    </el-result>
                </div>
            </el-main>
        </el-container>

        <!-- 医生详情对话框 -->
        <el-dialog
            v-model="doctorDetailVisible"
            title="医生详情"
            width="50%"
        >
            <div class="doctor-detail-content">
                <!-- 医生详细信息展示 -->
            </div>
        </el-dialog>

        
    </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElButton, ElMessage, ElMessageBox } from 'element-plus'
import { getHospital, getDepartment, getSchedule } from '@/api/getInfo'
import { Location, OfficeBuilding, Search, Back } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { createAppointment, getDoctorsByDate } from '@/api/appointment'

const router = useRouter()
// const defaultHospitalImage = require('@/assets/default-hospital.jpg')
// const defaultDoctorAvatar = require('@/assets/default-avatar.jpg')

const doctorMan = require('@/assets/svg/doctor_svg/doctor_M.svg')
const doctorWoman = require('@/assets/svg/doctor_svg/doctor_F.svg')

defineOptions({
    name: 'Appointment'
})

// 预约步骤 0:选择医院 1:选择科室 2:选择医生 3:确认预约 
const activeStep = ref(0)
// 搜索医院
const searchHospital = ref('')
// 搜索科室
const searchDepartment = ref('')
// 搜索医生
const searchDoctor = ref('')
// 医生详情对话框
const doctorDetailVisible = ref(false)

// 医院列表
const hospitals = ref([])
// 科室列表
const departments = ref([])
// 医生列表
const doctors = ref([])
// 获取今天的日期，格式化为 YYYY-MM-DD
const today = new Date();
const year = today.getFullYear();
const month = String(today.getMonth() + 1).padStart(2, '0'); // 月份从0开始计数
const day = String(today.getDate()).padStart(2, '0');
const todayFormatted = `${year}-${month}-${day}`;

const selectedDate = ref(todayFormatted)  // 设置默认值为今天

const options = computed(() => {
    const dates = [];
    const options = { weekday: 'short', month: '2-digit', day: '2-digit' };
    const today = new Date();

    for (let i = 0; i < 7; i++) {
        const date = new Date();
        date.setDate(today.getDate() + i);

        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
        const day = String(date.getDate()).padStart(2, '0');

        dates.push({
            value: `${year}-${month}-${day}`, // 手动构造 YYYY-MM-DD 格式
            label: date.toLocaleDateString('zh-CN', options), // 本地化显示
        });
    }
    console.log('dates',dates)

    return dates
})

// 监听日期变化，重新获取医生列表
watch(selectedDate, (newVal, oldVal) => {
    fetchDoctors(newVal)
})

// 当前选择的医院
const selectedHospital = ref(null)
// 当前选择的科室
const selectedDepartment = ref(null)
// 当前选择的医生
const selectedDoctor = ref(null)

// 筛选后的科室列表
const filteredDepartments = computed(() => {
    if (!searchDepartment.value) return departments.value
    return departments.value.filter(dept => 
        dept.name.toLowerCase().includes(searchDepartment.value.toLowerCase())
    )
})

// 筛选后的医生列表
const filteredDoctors = computed(() => {
    if (!searchDoctor.value) return doctors.value
    return doctors.value.filter(doctor => 
        doctor.name.toLowerCase().includes(searchDoctor.value.toLowerCase())
    )
})

// 添加医院筛选的计算属性
const filteredHospitals = computed(() => {
    if (!searchHospital.value) return hospitals.value
    return hospitals.value.filter(hospital => 
        hospital.name.toLowerCase().includes(searchHospital.value.toLowerCase())
    )
})

// 科室的图片地址
// const url = computed(()=>{
//     // 使用 require.context 来动态加载 SVG
//     const requireSvg = require.context('@/assets/svg/department_svg', false, /\.svg$/);
//     try {
//         return requireSvg(`./${}.svg`);
//     } 
//     catch (error) {
//         console.error('Error loading SVG:', error);
//         return ''; // 返回默认值或错误图标
//     }
// })

const depUrl = (name) => {
    // 使用 require.context 来动态加载 SVG
    const requireSvg = require.context('@/assets/svg/department_svg', false, /\.svg$/)
    try {
        return requireSvg(`./${name}.svg`)
    } 
    catch (error) {
        console.error('Error loading SVG:', error)
        return '' // 返回默认值或错误图标
    }
}
const hospitalUrl = (name) => {
    const requireImg = require.context('@/assets/image/hospital', false, /\.jpg$/)
    try {
        return requireImg(`./${name}.jpg`)
    }
    catch (error) {
        console.error('Error loading JPG:', error)
        return '' // 返回默认值或错误图标
    }
}

// 添加一个响应式对象来存储医生的排班信息
const doctorSchedules = ref({})
// 医生工作时间段
const doctorWorkTime = ref({})
// 预约对话框相关数据
const appointmentDialogVisible = ref(false)

// 时间列表
const timeList = ref([
    {value: '08:00:00-08:30:00', start: '08:00:00', end: '08:30:00'},
    {value: '08:30:00-09:00:00', start: '08:30:00', end: '09:00:00'},
    {value: '09:00:00-09:30:00', start: '09:00:00', end: '09:30:00'},
    {value: '09:30:00-10:00:00', start: '09:30:00', end: '10:00:00'},
    {value: '10:00:00-10:30:00', start: '10:00:00', end: '10:30:00'},
    {value: '10:30:00-11:00:00', start: '10:30:00', end: '11:00:00'},
    {value: '11:00:00-11:30:00', start: '11:00:00', end: '11:30:00'},
    {value: '11:30:00-12:00:00', start: '11:30:00', end: '12:00:00'},
    {value: '14:00:00-14:30:00', start: '14:00:00', end: '14:30:00'},
    {value: '14:30:00-15:00:00', start: '14:30:00', end: '15:00:00'},
    {value: '15:00:00-15:30:00', start: '15:00:00', end: '15:30:00'},
    {value: '15:30:00-16:00:00', start: '15:30:00', end: '16:00:00'},
    {value: '16:00:00-16:30:00', start: '16:00:00', end: '16:30:00'},
    {value: '16:30:00-17:00:00', start: '16:30:00', end: '17:00:00'}
])

// 选择预约时间
const selectedTime = ref('')
// 时间禁用状态
const timeDisabledStatus = reactive({})

// 选择预约时间
const makeAppointment = async (doctor) => {
    selectedDoctor.value = doctor
    timeDisabledStatus.value = {}

    // 计算每个时间段的禁用状态
    for (let time of timeList.value) {
        const isDisabled = await isTimeDisabled(time.start, time.end, doctor)
        timeDisabledStatus[time.value] = isDisabled
    }

    appointmentDialogVisible.value = true
}

// 判断时间段是否可用
const isTimeDisabled = async (timeStart, timeEnd, doctor) => {
    const now = new Date()
    const currentTime = now.toTimeString().slice(0, 5)
    // 获取今天的日期字符串
    const today = new Date().toISOString().split('T')[0]

    const doctorWorkTimes = await getSchedule({
        doctor_id: doctor.id,
        date: selectedDate.value
    });

    if (doctorWorkTimes.data?.length === 0) {
        return true // 如果没有工作时间，禁用时间段
    }

    const workStart = doctorWorkTimes.data[0].start_time
    const workEnd = doctorWorkTimes.data[0].end_time

    if(selectedDate.value === today) {
        if (currentTime >= timeEnd) {
            return true // 当前时间超过时间段的结束时间
        }
    }
    if (timeEnd <= workStart || timeStart >= workEnd) {
        console.log('timeStart', timeStart, 'workEnd', workEnd)
        return true // 时间段结束时间早于或开始时间晚于医生工作时间
    }
    return false // 否则时间段可用
}

watch(selectedTime, (newVal) => {
    console.log('selectedTime', newVal)
})

// 获取医院列表
async function fetchHospitals(search) {
    try {
        const response = await getHospital({name: search})
        hospitals.value = response.data
    } catch (error) {
        ElMessage.error('获取医院列表失败')
    }
}

// 获取科室列表
async function fetchDepartments() {
    try {
        const response = await getDepartment({
            hospital_id: selectedHospital.value?.id
        })
        departments.value = response.data
        console.log('部门数据',response.data)
    } catch (error) {
        ElMessage.error('获取科室列表失败')
    }
}

// 获取医生列表
async function fetchDoctors(data) {
    try {
        const response = await getDoctorsByDate({
            hospital_id: selectedHospital.value?.id,
            specialty: selectedDepartment.value?.name,
            date: data
        })
        doctors.value = response.data
        console.log('医生数据',response.data)
        // 为每个医生获取排班信息
        for (const doctor of doctors.value) {
            await fetchSchedule(doctor.id)
        }
    } catch (error) {
        ElMessage.error('获取医生列表失败')
    }
}

// 选择医院
function selectHospital(hospital) {
    selectedHospital.value = hospital
    activeStep.value = 1
    fetchDepartments()
}

// 选择科室
function selectDepartment(department) {
    selectedDepartment.value = department
    activeStep.value = 2
    fetchDoctors(selectedDate.value)
}

// 返回上一步
function goBack(step) {
    activeStep.value = step
}

// 显示医生详情
function showDoctorDetail(doctor) {
    selectedDoctor.value = doctor
    doctorDetailVisible.value = true
}

// 创建一个映射对象，将英文缩写转换为中文
const dayMap = {
    Mon: '周一',
    Tue: '周二',
    Wed: '周三',
    Thu: '周四',
    Fri: '周五',
    Sat: '周六',
    Sun: '周日'
};

// 获取排班信息
async function fetchSchedule(id) {
    try {
        const response = await getSchedule({
            doctor_id: id
        });

        // 将英文缩写转换为中文，并连接成字符串
        const scheduleText = response.data
            .map(item => dayMap[item.day_of_week] || item.day_of_week) // 使用映射进行转换
            .join('、');
        
        // 存储到响应式对象中
        doctorSchedules.value[id] = scheduleText;
    } catch (error) {
        ElMessage.error('获取排班信息失败');
        return '暂无排班';
    }
}


// 确认预约
const confirmAppointment = async () => {
    ElMessageBox.confirm(
        `
        医院： ${selectedHospital.value.name} <br>
        科室： ${selectedDepartment.value.name} <br>
        医生： ${selectedDoctor.value.name} <br>
        日期： ${selectedDate.value} <br>
        时段： ${selectedTime?.value?.slice(0,5)+'-'+selectedTime?.value.slice(9,14)}`,
        '请确认预约信息',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            dangerouslyUseHTMLString: true, // 允许使用 HTML
        })
        .then( async () => {
            const timeSlot = selectedTime.value.split('-')
            const response = await createAppointment({
                doctor_id: selectedDoctor.value?.id,
                patient_id: sessionStorage.getItem('user_id'),
                appointment_date: selectedDate.value,
                start: timeSlot[0],
                end: timeSlot[1],
                status: '待确认'
            })
            console.log('response',response)
            appointmentDialogVisible.value = false
            if(!response.status) {
                ElMessage({
                    type: 'success',
                    message: '预约成功'
                })
                activeStep.value = 3
            }
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消预约'
            })
        }
    )
}

// 重置预约
function resetAppointment() {
    activeStep.value = 0
    selectedHospital.value = null
    selectedDepartment.value = null
    selectedDoctor.value = null
    searchHospital.value = ''
    searchDepartment.value = ''
    searchDoctor.value = ''
    fetchHospitals()
}

// 跳转到用户中心
function goToUserCenter() {
    router.push('/user-center')
}

// 返回首页
function backToHome() {
    router.back()
}

// 初始化
fetchHospitals()
</script>

<style lang="scss" scoped>
.appointment {
    padding: 20px;
    min-height: calc(100vh - 70px);
    background-color: #f5f7fa;

    .back {
        padding: 0 20px;
        font-size: 20px;
        font-weight: 100;
    }

    .steps {
        margin-bottom: 30px;
        padding: 20px;
        background: #fff;
        border-radius: 4px;
    }

    .search-bar {
        display: flex;
        gap: 10px;
        margin-bottom: 20px;

        .search-input {
            width: 300px;
        }
    }

    .step-content {
        background-color: #fff;
        padding: 20px;
        border-radius: 4px;
        min-height: 400px;

        .step-title {
            font-size: large;
            margin: 15px 0;
        }
    }

    .hospital-card, .department-card, .doctor-card {
        margin-bottom: 20px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
            transform: translateY(-5px);
            box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        }
    }

    .hospital-info {
        display: flex;
        height: 135x;
        overflow: hidden;
        
        .hospital-image {
            width: 140px;
            margin: 30px;
            object-fit: fill;
        }

        .hospital-detail {
            display: flex;
            flex-direction: column;
            justify-content: space-around;
            padding: 14px;

            h3 {
                margin: 0;
                font-size: 16px;
                color: #303133;
                white-space: nowrap;
                text-overflow: ellipsis;
            }

            .address-text {
                display: flex;
                align-items: center;
                gap: 5px;
                margin: 8px 0;
                color: #909399;
                font-size: 13px;
            }

            .level-text {
                margin: 8px 0 0;
            }
        }
    }

    .department-info {
        text-align: center;
        padding: 20px;

        h3 {
            margin: 10px 0;
            color: #303133;
        }

        p {
            color: #909399;
            font-size: 13px;
            margin: 5px 0;
        }

        .doctor-count {
            margin-top: 10px;
            color: #409EFF;
        }
    }

    .doctor-info {
        display: flex;
        gap: 20px;
        margin-bottom: 15px;

        .doctor-avatar {
            width: 80px;
            height: 80px;
            object-fit: cover;
            border-radius: 8px;
        }

        .doctor-detail {
            flex: 1;

            h3 {
                margin: 0 0 10px;
                color: #303133;
            }

            p {
                margin: 5px 0;
            }

            .specialty {
                color: #606266;
                font-size: 13px;
            }

            .schedule {
                margin-top: 10px;
            }
        }
    }

    .action-buttons {
        display: flex;
        justify-content: flex-end;
        gap: 10px;
    }

    

}
</style>
